const axios = require('axios')
const dayjs = require('dayjs')
const duration = require('dayjs/plugin/duration')
const { baseURL, cookie, deviceId, bark } = require('./config')
require('./console')

dayjs.extend(duration)
let cookies = []

if (Array.isArray(cookie)) cookies = cookie
else if (cookie.indexOf('&') > -1) cookies = cookie.split('&')
else if (cookie.indexOf('\n') > -1) cookies = cookie.split('\n')
else cookies = [cookie]

cookies = cookies.filter(v => v)

let currentCookie = ''

if (!cookies.length) {
  console.log('未配置cookie, 程序终止')
  process.exit(1)
}

const xmAxios = axios.create()
const barkAxios = axios.create()

const MW_BASE_URL = baseURL + 'xmMw/'

xmAxios.interceptors.request.use(req => {
  req.headers['X-Requested-With'] = 'XMLHttpRequest'
  req.headers['Accept-Language'] = 'zh-cn'
  req.headers['MT-Request-ID'] = getGUID()
  req.headers[
    'User-Agent'
  ] = `Mozilla/5.0 (iPhone; CPU iPhone OS 14_8 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 moutaiapp/1.2.1 device-id/${deviceId || 'moutaiapp'
  }`
  req.headers['Referer'] =
    'https://h5.moutai519.com.cn/gux/game/main?appConfig=2_1_2'
  req.headers['Cookie'] = currentCookie
  req.headers['Accept'] = 'application/json, text/javascript, */*; q=0.01'
  req.headers['Content-Type'] = 'application/json'
  req.headers['MT-APP-Version'] = '1.0.0'
  req.headers['Origin'] = 'https://h5.moutai519.com.cn'
  return req
})

function getGUID(key = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx') {
  return key.replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0
    var v = c == 'x' ? r : (r & 0x3) | 0x8

    return v.toString(16)
  })
}

function log(...msg) {
  console.log(`账号${cookies.indexOf(currentCookie) + 1}`, ...msg)
}

function sendBarkMsg(msg) {
  log(msg)
  if (!bark) return false
  return barkAxios({
    method: 'get',
    url: `${bark}/${encodeURIComponent('xm')}/${encodeURIComponent(
      `账号${cookies.indexOf(currentCookie) + 1} ` + msg
    )}?group=${encodeURIComponent('xm')}`
  })
}

async function httpRequest(url, method = 'get', _data) {
  let params = ''
  let data = {}
  if (method === 'get') {
    params = _data
  } else {
    data = _data
  }
  return await xmAxios({
    url,
    method,
    data,
    params
  })
    .then(d => d.data)
    .catch(async d => {
      if (d.response.status === 500 && d.response.data) {
        return Promise.resolve(d.response.data)
      }
      if (d.response.status === 401 && d.response.data) {
        await sendBarkMsg(`登录失效, 请更新 cookie 配置`)
        return Promise.reject('登录失效')
      }
      log(d)
    })
}

function getCumulativelyApplyingDays() {
  console.log()
  log('获取累计申购天数: ')
  return httpRequest(
    baseURL + 'xmyApplyingReward/cumulativelyApplyingDays',
    'post',
    {}
  ).then(d => {
    if (d.code === 2000) {
      return d.data
    } else {
      log('获取信息失败', d.message || '')
      return Promise.reject()
    }
  })
}

function receiveCumulativelyApplyingReward() {
  console.log()
  log('领取连续申购奖励: ')
  return httpRequest(
    baseURL + 'xmyApplyingReward/receiveCumulativelyApplyingReward',
    'post',
    {}
  ).then(d => {
    if (d.code === 2000) {
      if (d.data.successfullyReceived) {
        log('连续申购奖励领取成功,奖励值:', d.data.rewardAmount);
      } else {
        log('连续申购奖励领取信息:', d.data);
      }
    } else {
      log('连续申购奖励领取失败', d.message || '')
      return Promise.reject()
    }
  })
}

function get7DaysContinuouslyApplyingProgress() {
  console.log()
  log('获取7天连续申购进度: ')
  return httpRequest(
    baseURL + 'xmyApplyingReward/7DaysContinuouslyApplyingProgress',
    'post',
    {}
  ).then(d => {
    if (d.code === 2000) {
      return d.data
    } else {
      log('获取信息失败', d.message || '')
      return Promise.reject()
    }
  })
}

function receive7DaysContinuouslyApplyingReward() {
  console.log()
  log('领取7天申购奖励: ')
  return httpRequest(
    baseURL + 'xmyApplyingReward/receive7DaysContinuouslyApplyingReward',
    'post',
    {}
  ).then(d => {
    if (d.code === 2000) {
      if (d.data.successfullyReceived) {
        log('连续7天申购奖励领取成功,奖励值:', d.data.rewardAmount);
      } else {
        log('连续7天申购奖励领取信息:', d.data);
      }
    } else {
      log('连续申购奖励领取失败', d.message || '')
      return Promise.reject()
    }
  })
}

async function init() {
  console.log('开始执行')
  let time = +dayjs().format('HH')
  if (time >= 9 && time < 20) {
    for await (i of cookies) {
      currentCookie = i
      try {
        //领取累计申购奖励
        let cumulativelyApplyingDays = await getCumulativelyApplyingDays()
        let applyingDays = cumulativelyApplyingDays.previousDays;
        if (cumulativelyApplyingDays.appliedToday) {
          applyingDays = applyingDays + 1
        }
        //判断是否需要领奖
        let isApply = 0
        if (applyingDays >= 7) {
          let day7 = cumulativelyApplyingDays.rewardReceived['7']
          if (!day7) {
            console.log('领取累计7天的申购奖励')
            await receiveCumulativelyApplyingReward()
          } else {
            console.log('已经领取7天的申购奖励')
          }
          if (applyingDays >= 14) {
            let day14 = cumulativelyApplyingDays.rewardReceived['14']
            if (!day14) {
              console.log('领取累计14天的申购奖励')
              await receiveCumulativelyApplyingReward()
            } else {
              console.log('已经领取14天的申购奖励')
            }
            if (applyingDays >= 21) {
              let day21 = cumulativelyApplyingDays.rewardReceived['21']
              if (!day21) {
                console.log('领取累计21天的申购奖励')
                await receiveCumulativelyApplyingReward()
              } else {
                console.log('已经领取21天的申购奖励')
              }
              if (applyingDays >= 28) {
                let day28 = cumulativelyApplyingDays.rewardReceived['28']
                if (!day28) {
                  console.log('领取累计28天的申购奖励')
                  await receiveCumulativelyApplyingReward()
                } else {
                  console.log('已经领取28天的申购奖励')
                }
              }
            }
          }
        }
        console.log('累计连续申购天数:', applyingDays)
        //领取7天连续申购奖励
        let days7ContinuouslyApplyingProgress = await get7DaysContinuouslyApplyingProgress()
        if (days7ContinuouslyApplyingProgress.rewardReceived) {
          console.log('7天连续申购奖励已经领取过了')
        } else {
          let previousProgress = days7ContinuouslyApplyingProgress.previousProgress;
          if (days7ContinuouslyApplyingProgress.appliedToday) {
            previousProgress = previousProgress + 1;
          }
          //判断是否可以领取
          if (previousProgress >= 7) {
            await receive7DaysContinuouslyApplyingReward()
          } else {
            console.log('不能领取,7天连续申购天数:', previousProgress)
          }
        }
      } catch (e) { }
    }
  } else {
    console.log()
    console.log('活动未开始')
  }

  console.log()
  console.log('脚本执行完毕')
  console.log()
}

exports.init = init
